package com.evil.activiti.listener;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.evil.activiti.enums.EventTypeEnum;
import com.evil.activiti.util.ActivityUtil;
import com.evil.application.api.RemoteApplicationOrderNodeService;
import com.evil.application.pojo.dto.order.node.ModifyOrderNodeDataReqDTO;
import com.evil.common.activiti.enums.HandleTypeEnum;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Map;

/**
 * 流程完成监听器
 *
 * @author 15587
 * @date 2022-08-08 00:00
 */
@Slf4j
@Component("TaskCompletedListener")
@AllArgsConstructor
public class TaskCompletedListener implements ExecutionListener {

    private final RemoteApplicationOrderNodeService remoteApplicationOrderNodeService;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void notify(DelegateExecution execution) {
        String eventName = execution.getEventName();
        FlowElement flowElement = execution.getCurrentFlowElement();
        Map<String, Object> variables = execution.getVariables();
        log.info("【流程完成监听器】，execution.getEventName参数：{}", eventName);
        log.info("【流程完成监听器】，节点id：{}, 节点name:{}", flowElement.getId(), flowElement.getName());
        log.info("【流程完成监听器】，execution.getVariables参数：{}", JSON.toJSONString(variables));

        // 开始事件
        if (EventTypeEnum.START.getEvent().equals(eventName)) {
            // 结束节点
            if (flowElement instanceof EndEvent) {
                // 覆盖订单节点数据
                ModifyOrderNodeDataReqDTO modifyOrderNodeDataReqDTO = new ModifyOrderNodeDataReqDTO();
                modifyOrderNodeDataReqDTO.setOrderId(execution.getVariable(ActivityUtil.getProcessOrderIdKey(), Long.class));
                modifyOrderNodeDataReqDTO.setIsCover(true);
                modifyOrderNodeDataReqDTO.setHandleType(HandleTypeEnum.APPROVED.getId());
                Long nodeId = ActivityUtil.restoreFlowNodeId(execution.getCurrentActivityId());
                modifyOrderNodeDataReqDTO.setNodeHandlersMap(MapUtil.of(nodeId, new ArrayList<>()));
                remoteApplicationOrderNodeService.modifyOrderNodeData(modifyOrderNodeDataReqDTO);
            }
        }
    }
}
